<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
import { questionTypeOptions, statusBg } from "../const"
import { Page } from '@vben/common-ui';
import { QuestionDetail, CorrectDetail } from './index'
import { getExamUsersAnswerApi, getExamUsersListApi, getExamUsersScoreApi, saveExamMarkScoreApi, completeExamMarkScoreApi } from "#/api/manage/examination-mgr"
import type { ExamData, ExamUser, QuestionCorrectType, Score } from "./examination"
import { ElMessage, ElMessageBox } from 'element-plus';
import { $t } from '#/locales'

const examData = ref<ExamData>({
  questionTitle: "",
  qtyList: []
})
const questionLoading = ref(false)
const correctLoading = ref(false)
const saveLoading = ref(false)
const correctedData = ref<QuestionCorrectType[]>([])
const examId = ref(route?.query?.id ?? '')
const orgId = ref(route?.query?.orgId ?? '')
const usersList = ref<ExamUser[]>([])
const correctUser = ref<ExamUser>()
const correctUserId = ref()
const activeName = ref<string>('aiCorrected')

const updateUser = (val: any) => {
  if (val) {
    correctUser.value = usersList.value.find(_ => _?.id === correctUserId.value)
    getExamUsersAnswer()
    getExamUsersScore()
    activeName.value = 'aiCorrected'
  }
}
const handleClick = () => { }

const createIdx = (idx: number) => {
  return new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(
    idx + 1,
  );
}

// 分类排序问题
const classifyQuestions = (list: any) => {
  return Object.values(
    list.reduce((acc: any, cur: any) => {
      if (!acc[cur.type]) {
        const typeName = questionTypeOptions.find(_ => _?.value === cur.type)?.label
        acc[cur.type] = {
          name: typeName ?? '',
          type: cur.type,
          typeSort: cur.typeSort,
          questions: []
        }
      }
      acc[cur.type].questions.push(cur)
      return acc
    }, {} as Record<string, any>)
  ).sort((a: any, b: any) => a.typeSort - b.typeSort) as any
}

const getExamUsersAnswer = () => {
  if (!correctUser.value) return

  const params = {
    examScoreId: correctUser.value.id
  }
  questionLoading.value = true
  getExamUsersAnswerApi(params).then((res) => {
    if (res) {
      const { questionTitle, datas } = res
      examData.value = {
        questionTitle,
        qtyList: classifyQuestions(datas)
      }
    }
  }).finally(() => {
    questionLoading.value = false
  })
}

const getExamUsersList = () => {
  const params = {
    examId: examId.value,
    orgId: orgId.value
  }
  getExamUsersListApi(params).then((res) => {
    if (res) {
      usersList.value = res
      if (res?.length > 0) {
        if (correctUserId.value) {
          correctUser.value = res.find((item: ExamUser) => item?.id === correctUserId.value)
        } else {
          const user = route?.query?.userId ? res.find((item: ExamUser) => item?.userId === route?.query?.userId) : res[0]
          correctUser.value = user
          correctUserId.value = user?.id
        }
        getExamUsersAnswer()
        getExamUsersScore()
      }
    }
  }).finally(() => { })
}

const getExamUsersScore = () => {
  if (!correctUser.value) return

  const params = {
    examScoreId: correctUser.value.id
  }
  correctLoading.value = true
  getExamUsersScoreApi(params).then((res) => {
    if (res) {
      const correctType = res.findIndex((item: { markMethod: string }) => item?.markMethod == 'aiReadyCorrect')
      activeName.value = correctType >= 0 ? 'aiCorrected' : 'aiNotCorrect'
      correctedData.value = classifyQuestions(res)
    }
  }).finally(() => {
    correctLoading.value = false
  })
}

const scoreUpdate = (data:any) => {
  const { score, question } = data
  if(question?.type === 'trueFalse' || question?.type === 'radio') {
    if (score > 0 && score < question.score) {
      question.result = ''
      question.actualScore = null
      return
    }
  }
  if (score === question.score) {
    question.result = 'allCorrect'
  } else if (score > 0 && score < question.score) {
    question.result = 'partCorrect'
  } else if (score === 0) {
    question.result = 'wrong'
  } else {
    question.result = ''
  }
  if (correctUser.value) {
    correctUser.value.score = flatMapData(correctedData.value).reduce((acc: number, item: any) => acc + item.score, 0)
  }
}

const flatMapData = (list: any) => {
  return list.flatMap((item: QuestionCorrectType) =>
    item.questions.map(q => ({
      id: q.id,
      correctConfidenceRate: q.correctConfidenceRate,
      score: q.actualScore !== null && q.actualScore >= 0 ? q.actualScore : null
    }))
  )
}

const saveExamMarkScore = (todo: any) => {
  if (!correctUser.value) return
  const params = {
    examScoreId: correctUser.value.id,
    datas: flatMapData(correctedData.value)
  }
  console.log(params)
  saveLoading.value = true
  saveExamMarkScoreApi(params).then((res) => {
    if (res) {
      ElMessage.success($t('common.saveTxt', [$t('common.successTxt')]))
      getExamUsersList()
      if (todo === 'next') {
        console.log('next')
        nextUser()
      }
    }
  }).finally(() => {
    saveLoading.value = false
   })
}
const nextUser = () => {
  console.log(usersList.value)
  const idx = usersList.value.findIndex(_ => _?.id === correctUserId.value)
  let nextIdx = 0
  if (usersList.value[idx + 1]) {
    nextIdx = idx + 1
    correctUserId.value = usersList.value[nextIdx]?.id
  } else {
    ElMessage.info($t('exam.lastPersonTxt'))
  }
  getExamUsersList()
}
const completeExamMarkScore = () => {
  if (!correctUser.value) return
  const finallData = flatMapData(correctedData.value)
  if (finallData.some((item: any) => item.score === null)) {
    ElMessageBox.confirm(
      $t('exam.taggleStuTxt'),
      $t('common.tipTxt'),
      {
        confirmButtonText: $t('common.submitTxt'),
        cancelButtonText: $t('common.cancelTxt'),
        type: 'warning',
      }
    )
      .then(() => {
        saveExamMarkScore('next')
      })
      .catch(() => { })
    return
  }
  ElMessageBox.confirm(
    `${$t('exam.checkoutScoreTxt', { score: correctUser.value?.score ?? 0 })}`,
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      const params = {
        examScoreId: correctUser.value?.id,
        datas: finallData
      }
      completeExamMarkScoreApi(params).then((res) => {
        if (res) {
          nextUser()
        }
      }).finally(() => { })
    })
    .catch(() => { })
}

const aiCorrectedData = computed(() => {
  return (key: string) => {
    const list =  correctedData.value
      .map((group: QuestionCorrectType) => {
        const filteredQuestions = group.questions.filter(q => q.markMethod === key)
        if (filteredQuestions.length > 0) {
          return {
            ...group,
            questions: filteredQuestions
          }
        }
        return null
      })
      .filter(Boolean)
    return list
  }
})

const statusBackgroundColor = computed(() => {
  const status = correctUser.value?.status ?? 'uncorrected'
  return statusBg[status as keyof typeof statusBg] || statusBg.uncorrected
})

onMounted(() => {
  getExamUsersList()
})
</script>

<template>
  <Page class="h-full">
    <div class="flex flex-col bg-[#fff] h-full rounded-sm">
      <div class="w-full h-[48px] text-[#191919] text-[16px] p-[16px] pb-[12px] border-b border-color:#DCDFE6">{{
        examData.questionTitle
      }}</div>
      <div class="flex-1 overflow-auto p-[16px] pt-[12px]">
        <div class="flex h-full overflow-hidden items-top">
          <!-- 左侧题目区 -->
          <div v-loading="questionLoading" class="flex-auto min-h-full pr-[30px] overflow-scroll">
            <QuestionDetail :examData="examData" :createIdx="createIdx"></QuestionDetail>
          </div>
          <!-- 右侧答题卡区 -->
          <div v-loading="correctLoading"
            class="flex-none w-[450px] max-h-full flex flex-col overflow-auto bg-[#F2F7FD] p-[16px] rounded-sm">
            <div class="title flex w-full h-[32px] leading-[32px] items-center justify-between text-[14px]">
              <div class="flex items-center">
                <span class="block text-[14px] w-[10px] h-[10px] rounded-[50%]"
                  :style="{ backgroundColor: statusBackgroundColor }"></span>
                <span v-if="correctUser?.status" class="text-[14px] status text-[#191919] ml-[5px] mr-[15px]">{{
                  $t(`exam.${correctUser?.status}Txt`) }}</span>
                <span class="exam-score text-[14px] text-[#191919]">{{ $t(`exam.examGradesTxt`) }}</span>
                <span class="text-[#E5484D] text-[14px] ml-[8px] font-[500]"> {{ `${correctUser?.score ??
                  '--'}${$t('exam.gradeTxt')}` }}</span>
              </div>
              <div class="flex items-center justify-end ml-[10px]">
                <span class="block w-[1px] h-[16px] border-l border-color:#DCDFE6 mr-[20px]"></span>
                <span class="name text-[#191919] text-[14px] mr-[8px]">{{ $t(`exam.examNamtTxt`) }}</span>
                <el-select v-model="correctUserId" size="default" filterable placeholder="" @change="updateUser"
                  class="w-[100px]" clearable>
                  <el-option v-for="item in usersList as any" :key="item?.id" :label="item?.name"
                    :value="item?.id"></el-option>
                </el-select>
              </div>
            </div>
            <el-tabs v-model="activeName" class="demo-tabs flex-1 overflow-auto" @tab-click="handleClick">
              <el-tab-pane class="h-full" v-if="aiCorrectedData('aiReadyCorrect')?.length > 0"
                :label="$t('exam.aiCorrectTxt')" name="aiCorrected">
                <CorrectDetail correctType="aiReadyCorrect" :listData="aiCorrectedData('aiReadyCorrect')"
                  @scoreUpdate="scoreUpdate" :createIdx="createIdx" :correctUser="correctUser">
                </CorrectDetail>
              </el-tab-pane>
              <el-tab-pane class="h-full" v-if="aiCorrectedData('aiNoCorrect')?.length > 0"
                :label="$t('exam.aiNotCorrectTxt')" name="aiNotCorrect">
                <CorrectDetail correctType="aiNoCorrect" :listData="aiCorrectedData('aiNoCorrect')"
                  @scoreUpdate="scoreUpdate" :createIdx="createIdx" :correctUser="correctUser">
                </CorrectDetail>
              </el-tab-pane>
            </el-tabs>
            <div class="flex justify-end">
              <el-button size="default"
                :loading="saveLoading"
                :disabled="correctUser?.status === 'corrected' || correctUser?.status === 'published'"
                @click="saveExamMarkScore">{{ $t('common.saveTxt') }}</el-button>
              <el-button :disabled="correctUser?.status === 'published'" size="default" type="primary"
                @click="completeExamMarkScore">{{ $t('exam.finishAndNextTxt')
                }}</el-button>
                <!-- <el-button :disabled="correctUser?.status === 'published'" size="default" type="primary"
                @click="nextUser">{{ $t('exam.finishAndNextTxt')
                }}</el-button> -->
                
            </div>
          </div>
        </div>
      </div>
    </div>
  </Page>
</template>

<style scoped lang="scss">
:deep(.el-input-number.is-without-controls .el-input__wrapper) {
  padding-left: 1px;
  padding-right: 1px;
}
</style>
